<template>
  <Layout>
    <div class="product-create-container">
      <div class="page-header">
        <div class="header-title">新建商品</div>
        <div class="header-actions">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleSubmit">提交商品</el-button>
        </div>
      </div>

      <el-form
        ref="formRef"
        :model="productForm"
        :rules="formRules"
        label-width="120px"
        class="product-form"
      >
        <!-- 基础信息 -->
        <div class="form-section">
          <div class="section-header">
            <div class="section-title">基础信息</div>
          </div>
          <div class="section-content">
            <el-form-item label="商品名称" prop="name">
              <el-input
                v-model="productForm.name"
                placeholder="请输入商品名称"
                maxlength="60"
                show-word-limit
              />
              <div class="form-tip">
                商品名称为文本输入框，必填。最多支持60个字符，支持中英文、数字和特殊字符。
              </div>
            </el-form-item>

            <el-form-item label="短标题" prop="shortTitle">
              <el-input
                v-model="productForm.shortTitle"
                placeholder="请输入短标题"
                maxlength="20"
                show-word-limit
              />
              <div class="form-tip">
                短标题为文本输入框，必填。最多支持20个字符，支持中英文、数字和特殊字符。
              </div>
            </el-form-item>

            <el-form-item label="商品分类" prop="category">
              <el-cascader
                v-model="productForm.category"
                :options="categoryOptions"
                placeholder="请选择分类"
                clearable
              />
              <div class="form-tip">
                商品分类为下拉选择组件，必填。点击选择分类按钮，弹出选择分类弹窗。
              </div>
            </el-form-item>

            <el-form-item label="品牌" prop="brand">
              <el-select
                v-model="productForm.brand"
                placeholder="请选择品牌"
                clearable
              >
                <el-option
                  v-for="item in brandOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <div class="form-tip">
                品牌管理为下拉选择组件，支持单选，非必填。
              </div>
            </el-form-item>

            <!-- 商品参数已移除 -->
          </div>
        </div>

        <!-- 图文信息 -->
        <div class="form-section">
          <div class="section-header">
            <div class="section-title">图文信息</div>
            <div
              class="section-subtitle"
              style="color: #f56c6c; margin-top: 5px; font-weight: bold"
            >
              请务必上传商品图片，第一张图片将作为主图
            </div>
          </div>
          <div class="section-content">
            <el-form-item label="商品主图">
              <div class="image-uploader">
                <el-upload
                  v-model:file-list="mainImageList"
                  :limit="5"
                  list-type="picture-card"
                  :auto-upload="false"
                  :on-preview="handlePictureCardPreview"
                  :on-remove="handleRemove"
                  :on-change="handleImageChange"
                  accept="image/*"
                >
                  <el-icon><Plus /></el-icon>
                </el-upload>
                <el-dialog v-model="dialogVisible">
                  <img w-full :src="dialogImageUrl" alt="Preview Image" />
                </el-dialog>
              </div>
              <div class="form-tip">
                <strong style="color: #f56c6c"
                  >请在此处上传商品主图，第一张图片将自动作为主图。必填，最多可上传5张图片。</strong
                >
              </div>
            </el-form-item>

            <el-form-item label="视频" prop="video">
              <div class="video-uploader">
                <el-upload
                  v-model:file-list="videoList"
                  :limit="1"
                  list-type="picture-card"
                  :auto-upload="false"
                  :on-change="handleVideoChange"
                >
                  <el-icon><Plus /></el-icon>
                </el-upload>
              </div>
              <div class="form-tip">
                视频为视频上传组件，非必填。支持mp4和mov格式宽高比为1:1的视频文件，大小在20mb以内。只能上传一个视频。
              </div>
            </el-form-item>

            <el-form-item label="商品介绍" prop="introduction">
              <el-input
                v-model="productForm.introduction"
                type="textarea"
                placeholder="请输入商品介绍"
                maxlength="100"
                show-word-limit
                rows="4"
              />
              <div class="form-tip">
                商品介绍为多行文本输入框，非必填。最多支持100个字符，50个汉字，支持中英文、数字和特殊字符。
              </div>
            </el-form-item>

            <el-form-item label="商品详情" prop="details">
              <div class="rich-editor">
                <!-- 富文本编辑器组件 -->
                <el-input
                  v-model="productForm.details"
                  type="textarea"
                  placeholder="请输入商品详情"
                  rows="10"
                />
              </div>
              <div class="form-tip">
                商品详情为富文本组件，使用百度的UEditor插件。
              </div>
            </el-form-item>
          </div>
        </div>

        <!-- 价格与库存 - 简化版 -->
        <div class="form-section">
          <div class="section-header">
            <div class="section-title">价格与库存</div>
          </div>
          <div class="section-content">
            <el-form-item label="商品价格" prop="price">
              <el-input
                id="simple-price"
                v-model="productForm.price"
                type="number"
                placeholder="请输入商品价格"
                min="0"
              >
                <template #prefix>
                  <span>¥</span>
                </template>
              </el-input>
              <div class="form-tip">请输入商品价格，必填，单位为元</div>
            </el-form-item>

            <el-form-item label="商品库存" prop="stock">
              <el-input
                id="simple-stock"
                v-model="productForm.stock"
                type="number"
                placeholder="请输入商品库存"
                min="0"
              />
              <div class="form-tip">请输入商品库存数量，必填</div>
            </el-form-item>
          </div>
        </div>

        <!-- 服务信息部分已简化，移除了这一部分 -->

        <div class="form-actions">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleSubmit">提交商品</el-button>
        </div>
      </el-form>
    </div>
  </Layout>
</template>

<script setup lang="ts">
import { ref, reactive, computed, nextTick, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import Layout from "@/components/Layout.vue";
import { getCategoryList } from "@/api/category";
import { getBrandList } from "@/api/brand";
import { createProduct, updateProduct, getProductDetail } from "@/api/product";
// import { uploadFile } from '@/utils/request'
import { cosUtil } from "@/utils/cos"; // 导入腾讯云COS工具类

// 路由实例
const router = useRouter();
const route = useRoute();
const formRef = ref();
const loading = ref(false);

// 表单数据 - 简化版
const productForm = reactive({
  name: "",
  shortTitle: "",
  category: [], // 使用分组作为类目
  brand: "",
  introduction: "",
  details: "",
  price: 0,
  stock: 0,
});

// 表单校验规则
const formRules = {
  name: [
    { required: true, message: "请输入商品名称", trigger: "blur" },
    { max: 60, message: "商品名称不能超过60个字符", trigger: "blur" },
  ],
  shortTitle: [
    { required: true, message: "请输入短标题", trigger: "blur" },
    { max: 20, message: "短标题不能超过20个字符", trigger: "blur" },
  ],
  category: [{ required: true, message: "请选择商品分类", trigger: "change" }],
  deliveryMethod: [
    { required: true, message: "请选择配送方式", trigger: "change" },
  ],
};

// 类目选项（使用分类数据）
const categoryOptions = ref<any[]>([]);

// 品牌选项
const brandOptions = ref<any[]>([]);

// 加载分类数据
const loadCategoryData = async () => {
  try {
    const response: any = await getCategoryList();
    const allCategories = response.results || [];

    // 构建树形结构
    const rootCategories = allCategories.filter(
      (item: any) => !item.parentIdas
    );
    const subCategories = allCategories.filter((item: any) => item.parentIdas);

    // 处理每个一级分类
    categoryOptions.value = rootCategories.map((root: any) => {
      const option = {
        value: root.objectId,
        label: root.name,
        children: [] as any[],
      };

      // 查找该一级分类下的所有二级分类
      const children = subCategories.filter(
        (sub: any) => sub.parentIdas === root.objectId
      );

      if (children.length > 0) {
        // 将二级分类添加到一级分类的children数组中
        option.children = children.map((child: any) => ({
          value: child.objectId,
          label: child.name,
        }));
      }

      return option;
    });

    console.log("分类选项加载完成:", categoryOptions.value);
  } catch (error) {
    console.error("获取分类数据失败:", error);
    ElMessage.error("获取分类数据失败");
  }
};

// 加载品牌数据
const loadBrandData = async () => {
  try {
    const response: any = await getBrandList();
    const brands = response.results || [];

    brandOptions.value = brands.map((brand: any) => ({
      value: brand.objectId,
      label: brand.name,
    }));

    console.log("品牌选项加载完成:", brandOptions.value);
  } catch (error) {
    console.error("获取品牌数据失败:", error);
    ElMessage.error("获取品牌数据失败");
  }
};

// 图片上传相关
const mainImageList = ref<any[]>([]);
const videoList = ref<any[]>([]);
const dialogImageUrl = ref("");
const dialogVisible = ref(false);

const handleRemove = (file: any) => {
  console.log(file);
};

const handlePictureCardPreview = (file: any) => {
  dialogImageUrl.value = file.url;
  dialogVisible.value = true;
};

const handleImageChange = (file: any) => {
  console.log("图片变更:", file);
  // 如果是新上传的图片，创建临时URL用于预览
  if (file.raw && !file.url) {
    file.url = URL.createObjectURL(file.raw);
  }
};

// 参数相关
// 参数功能已移除
const addParam = () => {
  console.log("参数功能已移除");
};

const removeParam = (index: number) => {
  console.log("参数功能已移除");
};

// 属性相关
const selectedColors = ref(["红色", "蓝色", "白色"]);
const selectedModels = ref(["250ml", "500ml", "990ml"]);
const colorInputVisible = ref(false);
const modelInputVisible = ref(false);
const colorInputValue = ref("");
const modelInputValue = ref("");
const colorInputRef = ref();
const modelInputRef = ref();

const showColorInput = () => {
  colorInputVisible.value = true;
  nextTick(() => {
    colorInputRef.value?.focus();
  });
};

const showModelInput = () => {
  modelInputVisible.value = true;
  nextTick(() => {
    modelInputRef.value?.focus();
  });
};

const addColor = () => {
  if (
    colorInputValue.value &&
    !selectedColors.value.includes(colorInputValue.value)
  ) {
    selectedColors.value.push(colorInputValue.value);
  }
  colorInputVisible.value = false;
  colorInputValue.value = "";
  updateSpecificationList();
};

const addModel = () => {
  if (
    modelInputValue.value &&
    !selectedModels.value.includes(modelInputValue.value)
  ) {
    selectedModels.value.push(modelInputValue.value);
  }
  modelInputVisible.value = false;
  modelInputValue.value = "";
  updateSpecificationList();
};

const removeColor = (color: string) => {
  const index = selectedColors.value.indexOf(color);
  if (index !== -1) {
    selectedColors.value.splice(index, 1);
  }
  updateSpecificationList();
};

const removeModel = (model: string) => {
  const index = selectedModels.value.indexOf(model);
  if (index !== -1) {
    selectedModels.value.splice(index, 1);
  }
  updateSpecificationList();
};

// 规格表相关
const specificationList = ref<any[]>([]);

const updateSpecificationList = () => {
  specificationList.value = [];

  // 根据选择的颜色和型号生成规格表
  selectedColors.value.forEach((color: string) => {
    selectedModels.value.forEach((model: string) => {
      specificationList.value.push({
        color,
        model,
        image: "",
        code: "",
        retailPrice: "",
        wholesalePrice: "",
        purchasePrice: "",
        stock: "",
      });
    });
  });
};

// 初始化规格表
updateSpecificationList();

// 视频上传相关
const handleVideoChange = (file: any) => {
  console.log("视频变更:", file);
  // 如果是新上传的视频，创建临时URL用于预览
  if (file.raw && !file.url) {
    file.url = URL.createObjectURL(file.raw);
  }
};

// 规格表图片上传处理
const handleSpecImageChange = (file: any, row: any) => {
  console.log("规格图片变更:", file, row);
  // 保存文件对象到规格行中
  row.imageFile = file;
  // 创建临时URL用于预览
  if (file.raw && !file.url) {
    file.url = URL.createObjectURL(file.raw);
    row.imagePreview = file.url;
  }
};

// 处理表单提交
const handleSubmit = async () => {
  console.log("点击提交商品按钮");

  if (!formRef.value) {
    console.error("表单引用不存在");
    return;
  }

  try {
    // 检查表单验证状态
    const valid = await formRef.value.validate().catch((err: any) => {
      console.error("表单验证错误:", err);
      return false;
    });

    // 手动检查图片是否上传，但允许跳过这个检查
    if (valid && (!mainImageList.value || mainImageList.value.length === 0)) {
      console.log("未上传图片，但允许继续提交");
    }

    console.log("表单验证结果:", valid);

    if (!valid) {
      ElMessage.warning("请填写必填字段");
      return;
    }

    // 如果没有上传图片，则提示但允许继续
    let useDefaultImage = false;
    if (mainImageList.value.length === 0) {
      console.log("未上传图片，但允许继续提交");
      useDefaultImage = true;
    }

    // 构建商品数据 - 简化版本，只保留基本字段
    const productData: any = {
      name: productForm.name,
      shortTitle: productForm.shortTitle,
      category:
        productForm.category.length > 0
          ? productForm.category[productForm.category.length - 1]
          : null,
      brand: productForm.brand || null,
      introduction: productForm.introduction,
      details: productForm.details,
      price: 0, // 默认价格，后续会被覆盖
      stock: 0, // 默认库存，后续会被覆盖
    };

    // 使用表单中的价格和库存数据
    productData.price = Number(productForm.price) || 0;
    productData.stock = Number(productForm.stock) || 0;

    console.log("价格和库存数据:", {
      price: productData.price,
      stock: productData.stock,
      formPrice: productForm.price,
      formStock: productForm.stock,
    });

    console.log("商品价格和库存:", {
      price: productData.price,
      stock: productData.stock,
    });

    loading.value = true;

    try {
      // 处理图片上传 - 使用腾讯云COS
      if (mainImageList.value && mainImageList.value.length > 0) {
        const imageUrls = [];

        try {
          // 遍历所有图片并上传
          for (const file of mainImageList.value) {
            if (file.url && !file.raw) {
              // 如果已经有URL（例如编辑时的已有图片），直接使用
              imageUrls.push(file.url);
            } else if (file.raw) {
              // 如果是新上传的图片，上传到腾讯云COS
              try {
                const url = await cosUtil.uploadFile(file.raw);
                imageUrls.push(url);
              } catch (error) {
                console.error("上传图片到腾讯云COS失败:", error);
                // 使用临时本地URL作为替代，仅用于演示
                if (file.url) {
                  console.log("使用临时本地URL替代:", file.url);
                  imageUrls.push(file.url);
                } else {
                  throw error;
                }
              }
            }
          }

          productData.mainImages = imageUrls;
          console.log("上传的图片URLs:", imageUrls);
        } catch (error) {
          console.error("处理图片上传过程中发生错误:", error);
          ElMessage.error(
            "上传图片失败: " +
              (error as Error).message +
              "。请检查腾讯云COS配置和CORS设置。"
          );
          loading.value = false;
          return;
        }
      } else if (useDefaultImage) {
        // 使用默认占位图作为主图
        productData.mainImages = ["https://placehold.co/600x400"];
      }

      // 处理视频上传 - 使用腾讯云COS
      if (videoList.value && videoList.value.length > 0) {
        const videoFile = videoList.value[0] as any;
        if (videoFile.url && !videoFile.raw) {
          // 如果已经有URL，直接使用
          productData.video = videoFile.url;
        } else if (videoFile.raw) {
          // 如果是新上传的视频，上传到腾讯云COS
          try {
            const url = await cosUtil.uploadFile(videoFile.raw);
            productData.video = url;
          } catch (error) {
            console.error("上传视频到腾讯云COS失败:", error);
            ElMessage.error("上传视频失败: " + (error as Error).message);
            loading.value = false;
            return;
          }
        }
      }

      // 简化版本不需要规格图片上传

      console.log("提交的商品数据:", productData);

      // 确保数据类型正确
      if (productData.mainImages && Array.isArray(productData.mainImages)) {
        // 确保URL是字符串类型
        productData.mainImages = productData.mainImages.map((url: any) =>
          String(url)
        );
      }

      // 确保规格数据正确
      if (
        productData.specifications &&
        Array.isArray(productData.specifications)
      ) {
        productData.specifications.forEach((spec: any) => {
          spec.retailPrice = Number(spec.retailPrice) || 0;
          spec.wholesalePrice = Number(spec.wholesalePrice) || 0;
          spec.purchasePrice = Number(spec.purchasePrice) || 0;
          spec.stock = Number(spec.stock) || 0;
        });
      }

      // 判断是新建还是编辑
      const isEdit = route.name === "ProductEdit";
      const productId = route.params.id;

      try {
        if (isEdit && productId) {
          // 编辑商品
          const result = await updateProduct(productId as string, productData);
          console.log("更新商品结果:", result);
          ElMessage.success("商品更新成功");
        } else {
          // 新建商品
          const result = await createProduct(productData);
          console.log("创建商品结果:", result);
          ElMessage.success("商品提交成功");
        }
      } catch (error: any) {
        console.error("API调用失败:", error);
        // 获取详细错误信息
        let errorMsg = "保存商品失败";
        if (error.response && error.response.data) {
          errorMsg += `: ${JSON.stringify(error.response.data)}`;
        } else if (error.message) {
          errorMsg += `: ${error.message}`;
        }
        ElMessage.error(errorMsg);
        loading.value = false;
        return;
      }
      router.push("/product");
    } catch (error) {
      console.error("保存商品失败:", error);
      ElMessage.error("保存商品失败: " + (error as Error).message);
    } finally {
      loading.value = false;
    }
  } catch (error) {
    console.error("表单验证或提交过程中发生错误:", error);
    ElMessage.error("提交失败: " + (error as Error).message);
  }
};

// 取消操作
const handleCancel = () => {
  ElMessageBox.confirm("确定要取消编辑吗？未保存的内容将丢失", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      router.push("/product");
    })
    .catch(() => {});
};

// 加载商品详情数据
const loadProductData = async (id: string) => {
  try {
    loading.value = true;
    const response: any = await getProductDetail(id);
    console.log("获取到的商品数据:", response);

    if (!response) {
      ElMessage.error("获取商品数据失败: 未找到商品信息");
      return;
    }

    // 填充表单数据
    productForm.name = response.name || "";
    productForm.shortTitle = response.shortTitle || "";
    // 处理分类 - 暂时跳过分类设置，避免类型错误
    // TODO: 修复类型问题后再处理分类
    productForm.brand = response.brand || "";
    productForm.introduction = response.introduction || "";
    productForm.details = response.details || "";
    productForm.price = Number(response.price) || 0;
    productForm.stock = Number(response.stock) || 0;

    // 处理商品图片
    if (
      response.mainImages &&
      Array.isArray(response.mainImages) &&
      response.mainImages.length > 0
    ) {
      const imageList = response.mainImages.map((url: string) => ({
        name: url.substring(url.lastIndexOf("/") + 1),
        url: url,
      }));
      mainImageList.value = imageList;
    }

    ElMessage.success("商品数据加载成功");
  } catch (error) {
    console.error("加载商品数据失败:", error);
    ElMessage.error("加载商品数据失败: " + (error as Error).message);
  } finally {
    loading.value = false;
  }
};

// 页面加载时初始化数据
onMounted(() => {
  loadCategoryData();
  loadBrandData();

  // 判断是否是编辑模式
  const isEdit = route.name === "ProductEdit";
  const productId = route.params.id;

  if (isEdit && productId) {
    // 如果是编辑模式，加载商品数据
    loadProductData(productId as string);
  }
});
</script>

<style scoped>
.product-create-container {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-title {
  font-size: 20px;
  font-weight: bold;
}

.form-section {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.section-header {
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  position: relative;
  padding-left: 10px;
}

.section-title::before {
  content: "";
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 16px;
  background-color: #409eff;
  border-radius: 2px;
}

.section-content {
  padding: 20px;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.params-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.param-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.param-name,
.param-value {
  width: 200px;
}

.image-uploader,
.video-uploader {
  margin-bottom: 10px;
}

.attributes-selector {
  margin-bottom: 20px;
}

.attribute-group {
  margin-bottom: 15px;
}

.attribute-name {
  font-weight: bold;
  margin-bottom: 8px;
}

.attribute-values {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
}

.attribute-input {
  width: 100px;
}

.periodic-limit {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-top: 10px;
}

.form-actions {
  display: flex;
  justify-content: center;
  margin-top: 30px;
  gap: 20px;
}

.spec-image-uploader :deep(.el-upload--picture-card) {
  width: 60px;
  height: 60px;
  line-height: 60px;
}

.spec-image-preview {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
</style>
